<!--
 * @Author: zhi1hw hanwei@zhi1tech.com
 * @Date: 2024-06-28 20:47:19
 * @LastEditors: zhi1hw hanwei@zhi1tech.com
 * @LastEditTime: 2024-09-29 15:56:05
 * @FilePath: \code\src\views\home\components\transfer.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div style="height: 100vh;" @click.stop v-loading="state.isShowLoadding" element-loading-text="Loading..."
    :element-loading-spinner="svg" element-loading-svg-view-box="-10, -10, 50, 50"
    element-loading-background="rgba(122, 122, 122, 0.8)">
    <div class="wrapper" v-if="!state.isShowLoadding">
      <div class="yindaoye">
        <div class="guide">
          <!-- <video
            class="video-background"
            id="video"
            loop
            muted
            playsinline
            preload="metadata"
            autoplay
            poster="@/assets/images/video-bg.jpg"
            x5-video-player-type="h5"
          >
            <source src="@/assets/images/guide-video.mp4" type="video/mp4" />
          </video> -->
          <!-- <img src="@/assets/images/video-bg.jpg" alt="" > -->
        </div>
        <div class="robot">
          <img src="@/assets/images/guide_rob.gif" alt="" />
          <printHtml :homeInfo="state.homeInfo" @listenPrintHtml="listenPrintHtml" />
          <!--          <div class="today-hot" v-if="state.homeInfo?.dailyNews">-->
          <div class="today-hot">
            <div v-if="state.isPrivileges">
              <div v-if="state.homeInfo?.dailyNews.length > 0">
                <div class="title">
                  <span>至一热搜</span> <span class="line"></span>
                  <span class="subtitle">最新内容早知道</span>
                </div>
                <div class="list">
                  <div class="nav-tab">
                    <div class="nav-item" :class="state.navIndex === index ? 'active' : ''"
                      v-for="(i, index) in state.homeInfo?.dailyNews?.map((j: any) => j.typeName)" :key="index"
                      @click="state.navIndex = index">
                      <div class="item-text"> {{ i }}</div>
                    </div>
                  </div>
                  <div
                    v-if="state.homeInfo?.dailyNews[state.navIndex].list && state.homeInfo?.dailyNews[state.navIndex].list.length > 0">
                    <div class="scroll-box">
                      <div class="item" v-for="i in state.homeInfo?.dailyNews[state.navIndex].list" :key="i"
                        @click="bindClick(i.quizContent)">
                        <div>
                          <div class="point"></div>
                          {{ i.quizContent }}
                        </div>
                        <div>
                          <img src="@/assets/images/arrow.png" alt="" />
                        </div>
                      </div>

                    </div>
                  </div>
                  <div v-else>
                    <van-empty image-size="0" description="小助手正在努力学习中" />
                  </div>
                </div>
                <div class="opt-text" @click="toHome" :class="state.isPrintEnd ? 'end-opt-text' : ''">
                  立即体验
                </div>
              </div>
            </div>
            <template v-else>
              <div class="title">
                <span class="privileges-span"> {{ state.firstFunctionApply ? '暂时没有权限哦！请点击下方按钮进行申请' : '您的申请正在审核中!'
                  }}</span>
              </div>
              <div class="list"></div>
              <div v-if="state.firstFunctionApply" title="小助手功能申请" :visible.sync="detailVisible" width="35%">
                <el-form class="applySubmit">
                  <el-input class="elInput" v-model="message" maxlength="50" placeholder="请输入申请原因" show-word-limit />
                  <!--                  <span v-if="state.isSubmitting">已经提交过了，请勿重复提交</span>-->
                  <el-button class="elButton" round type="primary" native-type="submit" :disabled="state.isSubmitting"
                    @click="onSubmit">
                    提交
                  </el-button>
                </el-form>
              </div>
            </template>
          </div>
        </div>
        <div class="transfer-header">
          <div class="weather">
            <div class="area">
              <span class="area-name" @click="state.isShowArea = true"><van-icon name="location-o" />{{
                state.homeInfo?.cityName || ""
                }}</span>
              <span v-if="state.homeInfo">
                <i :class="'qi-' + state.homeInfo?.currWeather?.icon"></i>
                <template v-if="state.homeInfo?.currWeather?.temp">
                  &nbsp;{{ state.homeInfo?.currWeather?.temp }}℃</template>

                &nbsp;&nbsp;&nbsp;{{ state.homeInfo?.currWeather?.text }}</span>
            </div>
            <span>{{ moment().format("MM-DD") }} &nbsp;&nbsp;
              {{ weekdays[moment().format("d")] }}</span>
          </div>
          <!-- <div class="skip" @click="toHome">跳过</div> -->
        </div>
        <div class="ver">{{ ver }}</div>
      </div>
    </div>



    <!-- <van-popup v-model:show="state.isShowArea" position="bottom" :style="{ height: '30%' }">
      <van-area title="地区选择" :area-list="areaList" :columns-num="2" @confirm="areaConfirm"
        @cancel="state.isShowArea = false" />
    </van-popup> -->
  </div>
</template>

<script setup lang="ts">
import { themeStore, ITheme } from "../store/modules/theme";
import { useRoute, useRouter } from "vue-router";
import printHtml from "./demo.vue";
import moment from "moment";
import { areaList } from "@vant/area-data";
const themeColor: ITheme = themeStore().theme;
import {
  ComponentInternalInstance,
  getCurrentInstance,
  inject,
  onMounted,
  onUnmounted,
  reactive,
  watch,
  defineProps,
  provide,
  ref,
} from "vue";
import { showDialog } from "vant";
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

provide("themeColor", themeColor);
const state = reactive({
  isLoadEnd: false,
  isPrintEnd: false,
  homeInfo: null,
  isShowBg: false,
  isShowArea: false,
  isShowLoadding: true,
  navIndex: 0,
  isSubmitting: false,
  isPrivileges: false,
  firstFunctionApply: false
});
const message = ref("");
const router = useRouter();
const listenPrintHtml = (e: boolean) => {
  state.isPrintEnd = e;
};
const weekdays = [
  "星期日",
  "星期一",
  "星期二",
  "星期三",
  "星期四",
  "星期五",
  "星期六",
];
// 省市区选择
const areaConfirm = (e: any) => {
  let homeInfo = JSON.parse(JSON.stringify(state.homeInfo));
  homeInfo.cityName = e.selectedOptions[e.selectedOptions.length - 1].text;
  localStorage.setItem("area", JSON.stringify(e));
  state.homeInfo = homeInfo;
  state.isShowArea = false;
  getHomeInfo(e.selectedOptions[e.selectedOptions.length - 1].text);
};
const toLogin = (code: any, isBackLoading: boolean, type: number) => {

  router.push('/home') 
  return
  // /dev/AI/wechatApi/login
  // /dev/AI/wechatApi/backLogin
  const url = isBackLoading
    ? process.env.VUE_APP_BASE_API_URL + "/wechatApi/backLogin"
    : process.env.VUE_APP_BASE_API_URL + "/wechatApi/login";
  proxy?.$api
    .post(url, {
      code: code,
      type: type,
    })
    .then((res: any) => {
      if (res) {
        if (res.code === 200 && res.data) {
          let email = res.data.user?.email?.split("@")[0];
          let isPrivileges = res.data.privileges;

          themeStore().setCount(email || "");
          localStorage.setItem("userInfo", JSON.stringify(res.data));
          localStorage.setItem("token", res.data.token);
          let area = localStorage.getItem("area")
            ? JSON.parse(localStorage.getItem("area"))
            : "";
          state.isPrivileges = isPrivileges;
          state.firstFunctionApply = res.data.firstFunctionApply
          console.log("res.data.userConfig && res.data.userConfig.length > 0 && res.data.userConfig[0].value != 'true'", res.data.userConfig && res.data.userConfig.length > 0 && res.data.userConfig[0].value != 'true')
          if (res.data.userConfig && res.data.userConfig.length > 0 && res.data.userConfig[0].value != 'true' && isPrivileges) {
            toHome()
          } else {
            getHomeInfo(
              area && area.selectedOptions
                ? area.selectedOptions[area.selectedOptions.length - 1].text
                : "上海"
            );
          }
          state.isShowLoadding = false;
        } else {
          if (type === 2) {
              if (process.env.NODE_ENV === "development") {
                // location.href = `${process.env.VUE_APP_BASE_API}AI/wechatApi/authorize`;
                state.isShowLoadding = false;
              } else if (process.env.NODE_ENV === "test") {
                location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
              } else if (process.env.NODE_ENV === "production") {
                location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
            }
          }
          //  if(/wxwork/i.test(navigator.userAgent)) {
          //   if(process.env.NODE_ENV === 'development') {
          //     location.href = `${process.env.VUE_APP_BASE_API}AI/wechatApi/authorize`;
          //   } else if(process.env.NODE_ENV === 'test') {
          //       location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
          //   } else {
          //       location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
          //   }
          // } else  if (/micromessenger/i.test(navigator.userAgent)) {
          //   // 微信浏览器
          // }
        }
      }
    });
};

const getServerIP = async () => {
  try {
    const response = await fetch('https://api.ipify.org?format=json');
    const data = await response.json();
    return data.ip;
  } catch (error) {
    console.error('Error fetching server IP:', error);
    return null;
  }
}

const getHomeInfo = async (city: string) => {
  proxy?.$api
    .get(process.env.VUE_APP_BASE_API_URL + "/wechatApi/getHomeInfo", {
      cityName: city || "",
      ip: await getServerIP()
    })
    .then((res: any) => {
      if (res.code === 200) {
        let area = localStorage.getItem("area")
          ? JSON.parse(localStorage.getItem("area"))
          : "";
        if (area) {
          res.data.cityName =
            area.selectedOptions[area.selectedOptions.length - 1].text;
        }
        localStorage.setItem("homeInfo", JSON.stringify(res.data));
        state.homeInfo = res.data;
        // if(localStorage.getItem('isPreview') === 'true') {
        //   proxy?.$router.replace({path: "/home", query:{
        //     sessionId: localStorage.getItem('sessionId'),
        //   }});
        // }
      }
    });
};
const bindClick = (e: string) => {
  if (!localStorage.getItem("userInfo")) {
    proxy?.$showToast("用户信息获取失败");
    return;
  }
  proxy?.$router.replace({
    path: "/home",
    query: {
      sendText: e,
    },
  });
};
const toHome = () => {
  if (!localStorage.getItem("userInfo")) {
    proxy?.$showToast("用户信息获取失败");
    return;
  }
  // location.href = "https://" + window.location.host + "/BeiGeneAI/#/home"
  proxy?.$router.replace("/home");
};
const ver = process.env.VUE_APP_VERSION;
const isMobile = function () {
  const userAgent = navigator.userAgent.toLowerCase();
  return /iphone|ipod|android|windows phone|blackberry|bb10|mobi|xoom|tablet|mobile/i.test(
    userAgent
  );
};
onMounted(() => {
  // localStorage.removeItem("userInfo");
  // localStorage.removeItem("token");

  // let params: any = proxy?.$utils.getUrlParam();
  // if (params && (params.code || params.userCode || params.id_token)) {
  //   const LOGIN_TYPE = params.code || params.userCode ? 2 : 1;
  //   toLogin(
  //     params.code || params.userCode || params.id_token || "",
  //     params.code || params.id_token ? false : true,
  //     LOGIN_TYPE
  //   );
  // } else {
  //     state.isShowLoadding = false
  //     if (process.env.NODE_ENV === "development") {
  //       // location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
  //       // location.href = `${process.env.VUE_APP_BASE_API}/PC/BeiGeneAI/#/transfer?userCode=john.oyler@beigene.com`;
  //     } else if (process.env.NODE_ENV === 'test') {
  //       location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorize`;
  //       if (isMobile()) {
  //         location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorize`;
  //       } else {
  //         location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
  //       }
  //     } else {
  //       location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorize`;
  //       if (isMobile()) {
  //         location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorize`;
  //       } else {
  //         location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
  //       }
  //     }
  // }
  // setTimeout(() => {
  //   state.isShowBg = true;
  // }, 5000);
  router.push('/home') 
});

const onSubmit = async () => {
  // if (state.isSubmitting) return;
  // 防止重复提交

  state.isSubmitting = true; // 设置为正在提交

  // 获取并解析用户信息
  let userInfo = localStorage.getItem("userInfo");
  if (userInfo) {
    userInfo = JSON.parse(userInfo); // 解析为对象
  } else {
    console.error('未找到用户信息');
    state.isSubmitting = false;
    return;
  }

  // 获取 user.email
  const email = userInfo.user?.email;
  if (!email) {
    console.error('用户邮箱未找到');
    state.isSubmitting = false;
    return;
  }

  try {
    // 构建请求体
    const requestBody = {
      email: email,  // 提交 user.email
      reason: message,
      isDispose: true,
      applyTime: Date.now(), // 使用 ISO 时间格式
    };
    const url = process.env.VUE_APP_BASE_API_URL + "/functionApply/insertFunctionApply"
    proxy?.$api
      .post(url, requestBody).then((res: any) => {
        if (res.code == 200) {
          state.isSubmitting = true;
          state.firstFunctionApply = false;
          showDialog({
            message: '申请成功!'
          });
        } else {
          showDialog({
            message: res.msg
          });
        }
      })
    // proxy?.$router.replace("/home");
  } catch (error) {
    // 处理错误
    console.error('提交失败:', error);
  } finally {
    state.isSubmitting = false;// 恢复状态
  }
};
// 加载图片
const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `

</script>

<style lang="scss" scoped>
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;

  .yindaoye {
    .transfer-header {
      position: absolute;
      top: 30px;
      padding: 0 30px;
      display: flex;
      justify-content: space-between;
      width: 100%;
      left: 0;
      z-index: 102;

      .weather {
        font-size: 28px;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 40px;
        color: #28334a;
        text-align: left;
        vertical-align: top;
        display: flex;
        justify-content: space-between;
        width: 100%;

        .area {
          display: flex;
          align-items: center;
        }

        span {
          display: block;
          margin-bottom: 5px;
          margin-right: 20px;
        }
      }
    }

    .skip {
      padding: 12px 28px;
      height: 68px;
      border-radius: 40px;
      background: rgba(0, 45, 87, 0.2);
      font-size: 32px;
      font-weight: 500;
      letter-spacing: 0px;
      color: #ffffff;
    }

    .guide {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: -1;
      background: url("../assets/images/guide_bg.gif") 0 1750px;
      background-size: cover;

      .video-background {
        width: 100%;
      }

      img {
        width: 100%;
      }
    }

    .robot {
      position: absolute;
      left: 0;
      right: 0;
      top: 10%;
      margin: auto;
      text-align: center;
      z-index: 100;

      .today-hot {
        font-size: 0;
        border-radius: 20px;
        background: rgba(255, 255, 255);
        box-shadow: 0px 0px 10px rgba(0, 125, 235, 0.3);
        padding: 34px 42px;
        width: 80%;
        margin: 0 auto;

        .scroll-box {
          overflow: scroll;

          .item{
            padding: 14px;
            div{
              font-size: 20px;
            }
          }

          &::-webkit-scrollbar {
            display: none;
          }
        }

        .title {
          font-size: 32px;
          font-weight: 400;
          letter-spacing: 0px;
          color: #5393cf;
          text-align: left;
          font-weight: bold;
          float: left;
          clear: both;
          display: block;
          width: 100%;
          display: flex;
          align-items: center;
          gap: 18px;

          .line {
            width: 1px;
            height: 30px;
            opacity: 1;
            background: rgba(83, 147, 207, 1);
          }

          .applySubmit {
            font-size: 0;
            display: block;
            width: 100px;
            display: flex;
            align-items: center;
          }

          .subtitle {
            font-size: 28px;
            font-weight: 400;
            letter-spacing: 0px;
            line-height: 33.6px;
            color: rgba(83, 147, 207, 0.5);
            text-align: left;
            padding-top: 2px;
          }
        }

        .list {
          font-size: 16px;
          width: 100%;
          clear: both;

          .nav-tab {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;

            .nav-item {
              font-size: 24px;
              font-weight: 500;
              letter-spacing: 0px;
              line-height: 38px;
              color: rgba(83, 147, 207, .5);
              text-align: left;
              vertical-align: top;
              position: relative;

              .item-text {
                position: relative;
                z-index: 2;
              }

              &.active {
                color: #333;

                &::after {
                  content: "";
                  display: block;
                  position: absolute;
                  background: linear-gradient(153.12deg, rgba(92, 178, 255, 1) 17.78%, rgba(255, 177, 177, 1) 100%);
                  height: 8px;
                  width: 100%;
                  bottom: 2px;
                  z-index: 1;
                }
              }

            }
          }

          .item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            opacity: 1;
            border-radius: 12px;
            background: rgba(83, 147, 207, 0.1);
            border-radius: 12px;
            margin-top: 12px;
            font-size: 24px;
            font-weight: 400;
            letter-spacing: 0px;
            line-height: 40px;
            color: rgba(83, 147, 207, 1);
            text-align: left;
            vertical-align: top;
            padding: 14px;

            &>div {
              display: flex;
              align-items: center;
            }

            .point {
              width: 5px;
              height: 5px;
              opacity: 1;
              background: #5393cf;
              border-radius: 50%;
              margin-right: 16px;
            }
          }
        }
      }

      .opt-text {
        padding: 14px 0;
        border-radius: 44px;
        background: rgba(83, 147, 207, 1);
        box-shadow: 0px 4px 4px rgba(81, 136, 184, 0.5);
        font-size: 20px;
        font-weight: 700;
        letter-spacing: 0px;
        color: #ffffff;
        width: 200px;
        margin: 40px auto 0;
        opacity: 0;
      }

      .end-opt-text {
        animation: upDown 500ms ease-in-out;
        opacity: 1;
      }

      img {
        width: 20%;
        margin-top: -4%;
      }
    }
  }

  .ver {
    position: absolute;
    bottom: 14px;
    left: 0;
    right: 0;
    margin: auto;
    text-align: center;
    z-index: 100;
    color: #4c4c4c;
    font-size: 20px;
    opacity: .5;
  }
}

::v-deep .htmltext {
  margin: -55px 0 10px 0;

  &>span {
    font-size: 26px;
    // font-weight: 700;
    letter-spacing: 0px;
    color: #003a70;
  }

  &>p {
    font-size: 14px;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 26px;
    color: rgba(0, 58, 112, 1);
    margin-top: 9px;

    span {
      display: block;
      margin-top: 6px;
    }
  }
}

@keyframes upDown {
  0% {
    margin-top: 300px;
    opacity: 0;
  }

  100% {
    margin-top: 10%;
    opacity: 1;
  }
}

.title {
  height: auto;
}

.privileges-span {
  font-size: 18px;
  text-align: center;
}

.example-showcase .el-loading-mask {
  z-index: 9;
}
  
</style>
<style lang="scss">
  .applySubmit{
    width: 80%;
    margin: 0 auto;
    .elInput{
      padding: 20px 0 40px;
    }
  }
</style>